package com.offdissys.common.core.handler;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.offdissys.common.core.response.Result;
import com.offdissys.common.core.web.domain.ResultBuilder;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @author ZhangHaiWen
 * @title: ResponseBodyAdvice
 * @projectName offline-discount-sys
 * @description: 全局统一异常处理类
 * @date 2022/3/179:45
 */
@ControllerAdvice
public class GlobalResponseBodyAdvice implements ResponseBodyAdvice {

    /**
     * 这个方法表示对于哪些请求要执行 beforeBodyWrite，返回 true 执行，返回 false 不执行
     * @param methodParameter
     * @param aClass
     * @return
     */
    @Override
    public boolean supports(MethodParameter methodParameter, Class aClass) {
        return true;
    }

    /**
     *
     * @param o
     * @param methodParameter
     * @param mediaType
     * @param aClass
     * @param serverHttpRequest
     * @param serverHttpResponse
     * @return
     */
    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        // 如果返回体已经是 Result 类型，则不必再次包装
        if (o instanceof Result) {
            return o;
        }
        return ResultBuilder.SUCCESS(o);
    }
}
